package com.yusiji.config;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.startup.Tomcat;

import java.io.File;

public class SpringApplication {

    public static void run(){
        try {
            Tomcat tomcat = new Tomcat();
            tomcat.setPort(8080);
            File baseDir =  createTempDir("tomcat");
            Context context = tomcat.addContext("/", baseDir.getAbsolutePath());
            context.addLifecycleListener((LifecycleListener) Class.forName(tomcat.getHost().getConfigClass())
                    .getConstructor().newInstance());
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    private static File createTempDir(String prefix) {
        try {
            File tempDir = File.createTempFile(prefix + ".", ".8080");
            tempDir.delete();
            tempDir.mkdir();
            tempDir.deleteOnExit();
            return tempDir;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
